#include "ProfileManager.h"

#include <fstream>
#include <iostream>

#include "boost/regex.hpp"


const string ProfileManager::RDT_CMD = "rdesktop ";
const string ProfileManager::CONFIG_PROFILE_DIR = "PROFILE_DIR";


ProfileManager::ProfileManager(const string& strConfigFile)
{
    this->strConfigFile = strConfigFile;

    string strLine;
    string::size_type nPos;
    ifstream inFile( strConfigFile.c_str() );

    while ( getline(inFile, strLine) )
    {
        nPos = strLine.find_first_of('=');
        configration[strLine.substr(0, nPos)] = strLine.substr(nPos + 1);
    }
}


bool
ProfileManager::setConfigration(Configration& configration)
{
    string strConfig;

    Configration::const_iterator it;
    for(it = configration.begin(); it != configration.end(); it++)
    {
        strConfig.append(it->first).append("=").append(it->second).append("\n");
    }

    return writeFile(strConfigFile, strConfig);
}


string
ProfileManager::getCommandLine(Arguments& arguments)
{
    string strCmd;

    strCmd.append(RDT_CMD).append("-a 16 -g 1680x1050");

    Arguments::const_iterator it;
    for(it = arguments.begin(); it != arguments.end(); it++)
    {
        if (it->first != RDT_PARAM_SERVER)
        {
            strCmd.append(" -").push_back(it->first);
            strCmd.append(" ").append(it->second);
        }
    }

    strCmd.append(" ").append(arguments[RDT_PARAM_SERVER]);

    return strCmd;
}


bool
ProfileManager::writeFile(const string& strFilePath, const string& strText)
{
    ofstream outFile( strFilePath.c_str() );

    if (!outFile) return false;

    outFile << strText << endl;

    outFile.close();

    return true;
}


void
ReplaceAll(string& str1, string strPattern, string str2)
{
    boost::regex re(strPattern);
    str1 = boost::regex_replace(str1, re, str2);
}


vector<string>
split(const string& str, const string& delims)
{
    string::size_type lastPos = str.find_first_not_of(delims, 0);
    string::size_type pos     = str.find_first_of(delims, lastPos);

    vector<string> tokens;

    while (string::npos != pos || string::npos != lastPos)
    {
        tokens.push_back(str.substr(lastPos, pos - lastPos));
        lastPos = str.find_first_not_of(delims, pos);
        pos     = str.find_first_of(delims, lastPos);
    }

    return tokens;
}
